#include "widget.h"
#include "ui_widget.h"
#include<QColor>
#include <QKeyEvent>
#include<QPoint>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);


    startx=30;
    starty=30;
    step=30;
    height=size().height();
    width=size().width();
    pix=new QPixmap(width,height);
    pix->fill(Qt::white);
    setMinimumSize(800,600);
    setMaximumSize(800,600);

    img.load("D:/job/qt/work/teacher/day3/QKeyEventProssss/butterfly1.png");




    setWindowTitle("键盘事件测试，控制蝴蝶动向");
    setAutoFillBackground(true);
    setPalette(Qt::white);



    drawPicturefun();//调用函数绘制
    resize(800,600);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::drawPicturefun()
{
  QPainter *painter=new QPainter;

  pix->fill(Qt::green);
  QPen pen;
  pen.setStyle(Qt::DotLine);
  painter->setPen(pen);

  for(int i=step;i<width;i=i+step)
  {
      painter->begin(pix);
//      painter->setPen(pen);
      painter->drawLine(QPoint(i,0),QPoint(i,height));
      painter->end();

  }
  for(int j=step;j<height;j=j+step)
  {
      painter->begin(pix);
//      painter->setPen(pen);
      painter->drawLine(QPoint(0,j),QPoint(width,j));
      painter->end();
  }

  painter->begin(pix);
  painter->drawImage(QPoint(startx,starty),img);
  painter->end();

}

void Widget::mousePressEvent(QMouseEvent *event)
{
    startx=event->x();
    starty=event->y();
    drawPicturefun();
    update();
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    startx=startx-startx%step;
    starty=starty-starty%step;
    if(event->key()==Qt::Key_Left)
    {
        startx=(startx-step<0)? startx:startx-step;

    }
    if(event->key()==Qt::Key_Right)
    {
        startx=(startx+step+img.width()>width)?startx:startx+step;
    }

    if(event->key()==Qt::Key_Up)
    {
        starty=(starty-step<0)? starty:starty-step;

    }
    if(event->key()==Qt::Key_Down)
    {
        starty=(starty+step+img.height()>height)?starty:starty+step;
    }
    drawPicturefun();
    update();
}

void Widget::paintEvent(QPaintEvent *event)
{
  QPainter  painter1;
  painter1.begin(this);
  painter1.drawPixmap(QPoint(0,0),*pix);
}
